package com.changzhou.chatroom.interceptor;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Arrays;
import java.util.List;

@Component
@Slf4j
public class JwtTokenUserInterceptor implements HandlerInterceptor {

    // 放行路径列表
    private static final List<String> EXCLUDE_PATHS = Arrays.asList(
            "/login.html", "/register.html", "/user/login", "/user/register",
            "/css/", "/js/", "/img/", "/favicon.ico"
    );

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String path = request.getRequestURI();
        // 放行静态资源和无需鉴权接口
        for (String exclude : EXCLUDE_PATHS) {
            if (path.startsWith(exclude)) {
                return true;
            }
        }

        HttpSession session = request.getSession(false);
        String token = session != null ? (String) session.getAttribute("token") : null;

        // 检查token是否存在
        if (token == null || token.isBlank()) {
            log.warn("未检测到有效Token，重定向到登录页面: {}", path);
            if (!response.isCommitted()) {
                response.sendRedirect(request.getContextPath() + "/login.html");
            }
            return false;
        }

        // TODO: 校验JWT有效性（如有工具类可调用）
        // if (!jwtUtil.validateToken(token)) {
        //     log.warn("Token无效，重定向到登录页面: {}", path);
        //     response.sendRedirect(request.getContextPath() + "/login.html");
        //     return false;
        // }

        return true;
    }
}